package com.loobot.album.exception;
import com.loobot.album.net.ErrorCode;
import com.loobot.album.net.RestResultGenerator;
import com.loobot.album.utils.JsonUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Ike.Fan
 * @date: 2018/11/20.
 */
@ControllerAdvice
//如果返回的为json数据或其它对象，添加该注解
@ResponseBody
public class GlobalExceptionHandler {

    //添加全局异常处理流程，根据需要设置需要处理的异常，本文以MethodArgumentNotValidException为例
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object MethodArgumentNotValidHandler(HttpServletRequest request,
                                                MethodArgumentNotValidException exception) throws Exception {
        //按需重新封装需要返回的错误信息
        List<ArgumentErr> invalidArguments = new ArrayList<>();
        //解析原错误信息，封装后返回，此处返回非法的字段名称，原始值，错误信息
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            ArgumentErr invalidArgument = new ArgumentErr(error.getDefaultMessage(), error.getField(), error.getRejectedValue());
            invalidArguments.add(invalidArgument);
        }

        return RestResultGenerator.genErrorResult(ErrorCode.ARGUMENT_ERR.getCode(), JsonUtils.toJson(invalidArguments));
    }

    @ExceptionHandler(value = AppException.class)
    public Object ExceptionHandler(HttpServletRequest request,
                                   AppException exception) throws Exception{
        return RestResultGenerator.genErrorResult(exception.getCode(), exception.getMessage());
    }
}
